<template>
  <div class="login-container">
    <transition name="fade-top">
      <a-form
        v-show="visible.isPwd === 0"
        id="components-form-demo-normal-login"
        :form="form"
        class="login-form"
      >
        <div class="login-title">
          <span>{{ title }}</span>
        </div>
        <div class="input-ctn">
          <div class="input-item">
            <a-icon
              slot="prefix"
              type="user"
              style="color: rgba(232, 240, 254, 1); font-size: 20px"
            />
            <input
              v-model.trim="form.username"
              placeholder="请输入手机号"
              @blur="handleBlur($event, 'username', 0)"
            />
          </div>
          <span
            :style="{ opacity: validate.username < 2 ? 1 : 0 }"
            style="height: 18.5px; display: block"
          >{{ validateText.username[validate.username] }} </span>
        </div>
        <div class="input-ctn">
          <div class="input-item">
            <a-icon
              slot="prefix"
              type="lock"
              style="color: rgba(232, 240, 254, 1); font-size: 20px"
            />
            <input
              v-model.trim="form.password"
              type="password"
              placeholder="请输入密码"
              @blur="handleBlur($event, 'password', 0)"
              @keydown.enter="handleSubmit"
            />
          </div>
          <span
            :style="{ opacity: validate.password < 2 ? 1 : 0 }"
            style="height: 18.5px; display: block"
          >{{ validateText.password[validate.password] }} </span>
        </div>
        <template v-if="isDev">
          <p style="color: white">下面这个仅node运行时显示</p>
          <a-button @click="
              form.password = 'Star*2017'
              handleSubmit()
            ">
            Star*2017
          </a-button>
          <a-button @click="
              form.password = 'CscecXn*2020'
              handleSubmit()
            ">
            CscecXn*2020
          </a-button>
        </template>
        <div class="tool-box">
          <a-checkbox v-model="isRemeber"> 记住密码 </a-checkbox>
          <span
            class="pointer"
            @click="visible.isPwd = 2"
          >忘记密码?</span>
        </div>
        <div style="margin-top: 50px">
          <a-button
            type="primary"
            :loading="loading"
            class="login-form-button"
            @click="handleSubmit"
          > 立即登录 </a-button>
        </div>
      </a-form>
    </transition>
    <!-- 修改初始密码 -->
    <transition name="fade-bottom">
      <a-form
        v-show="visible.isPwd === 1"
        id="components-form-demo-normal-login"
        :form="form1"
        class="login-form"
      >
        <div class="extraAction-wrapper">
          <div
            class="top-line-wrapper"
            title="返回登录"
            @click="visible.isPwd = 0"
          >
            <div class="img-wrapper">
              <img
                class="img"
                src="~@/assets/user/login/line.png"
                alt=""
              />
            </div>
          </div>
          <div class="sub-title">系统检测到您当前密码为初始密码,请修改后登录</div>
          <div class="input-ctn">
            <div class="input-item">
              <a-icon
                slot="prefix"
                type="user"
                style="color: rgba(232, 240, 254, 1); font-size: 20px"
              />
              <input
                v-model.trim="form1.username"
                placeholder="请输入手机号"
                readonly="readonly"
              />
            </div>
            <span style="opacity: 0; height: 18.5px; display: block" />
          </div>
          <div class="input-ctn">
            <div class="input-item">
              <a-icon
                slot="prefix"
                type="lock"
                style="color: rgba(232, 240, 254, 1); font-size: 20px"
              />
              <input
                ref="password1"
                v-model.trim="form1.password"
                type="text"
                placeholder="请输入新密码"
                @focus="handleFocus($event, 'password')"
                @blur="handleBlur($event, 'password', 1)"
                @keydown.enter="updateInitialPassword"
              />
            </div>
            <span
              :style="{ opacity: validate1.password < 2 ? 1 : 0 }"
              style="min-height: 18.5px; display: block"
            >{{ validateText1.password[validate1.password] }} </span>
          </div>
          <div class="input-ctn">
            <div class="input-item">
              <a-icon
                slot="prefix"
                type="lock"
                style="color: rgba(232, 240, 254, 1); font-size: 20px"
              />
              <input
                ref="passwordAgain1"
                v-model.trim="form1.passwordAgain"
                type="text"
                placeholder="请再次输入新密码"
                @focus="handleFocus($event, 'passwordAgain')"
                @blur="handleBlur($event, 'passwordAgain', 1)"
                @keydown.enter="updateInitialPassword"
              />
            </div>
            <span
              :style="{ opacity: validate1.passwordAgain < 2 ? 1 : 0 }"
              style="height: 18.5px; display: block"
            >{{ validateText1.passwordAgain[validate1.passwordAgain] }} </span>
          </div>
          <div style="margin-top: 50px">
            <a-button
              type="primary"
              :loading="loading"
              class="login-form-button"
              @click="updateInitialPassword"
            > 确定修改 </a-button>
          </div>
        </div>
      </a-form>
    </transition>
    <!-- 修改初始密码 -->
    <!-- 找回密码 -->
    <transition name="fade-bottom">
      <a-form
        v-show="visible.isPwd === 2"
        id="components-form-demo-normal-login"
        :form="form1"
        class="login-form"
      >
        <div class="extraAction-wrapper">
          <div
            class="top-line-wrapper"
            title="返回登录"
            @click="visible.isPwd = 0"
          >
            <div class="img-wrapper">
              <img
                class="img"
                src="~@/assets/user/login/line.png"
                alt=""
              />
            </div>
          </div>
          <div class="login-title">
            <span>找回密码</span>
          </div>
          <div class="input-ctn">
            <div class="input-item">
              <a-icon
                slot="prefix"
                type="user"
                style="color: rgba(232, 240, 254, 1); font-size: 20px"
              />
              <input
                v-model.trim="form2.username"
                placeholder="请输入手机号"
                @blur="handleBlur($event, 'username', 2)"
              />
            </div>
            <span
              :style="{ opacity: validate2.username < 2 ? 1 : 0 }"
              style="height: 18.5px; display: block"
            >{{ validateText2.username[validate2.username] }} </span>
          </div>
          <div class="input-ctn">
            <div class="input-item">
              <a-icon
                slot="prefix"
                type="safety-certificate"
                style="color: rgba(232, 240, 254, 1); font-size: 20px"
              />
              <input
                v-model.trim="form2.code"
                placeholder="请输入验证码"
                style="flex: 1"
                @blur="handleBlur($event, 'code', 2)"
              />
              <div class="code-btn-wrapper">
                <button
                  class="code-btn"
                  type="button"
                  :disabled="(second > 0 && second < 60) || sending"
                  @click="sendCode"
                >
                  <template v-if="second > 0 && second < 60"> {{ second }} </template>{{ codeText }}
                </button>
              </div>
            </div>
            <span
              :style="{ opacity: validate2.code < 2 ? 1 : 0 }"
              style="height: 18.5px; display: block"
            >{{ validateText2.code[validate2.code] }} </span>
          </div>
          <div class="input-ctn">
            <div class="input-item">
              <a-icon
                slot="prefix"
                type="lock"
                style="color: rgba(232, 240, 254, 1); font-size: 20px"
              />
              <input
                ref="password2"
                v-model.trim="form2.password"
                type="text"
                placeholder="请输入新密码"
                @focus="handleFocus($event, 'password')"
                @blur="handleBlur($event, 'password', 2)"
                @keydown.enter="retrievePassword"
              />
            </div>
            <span
              :style="{ opacity: validate2.password < 2 ? 1 : 0 }"
              style="min-height: 18.5px; display: block"
            >{{ validateText2.password[validate2.password] }} </span>
          </div>
          <div class="input-ctn">
            <div class="input-item">
              <a-icon
                slot="prefix"
                type="lock"
                style="color: rgba(232, 240, 254, 1); font-size: 20px"
              />
              <input
                ref="passwordAgain2"
                v-model.trim="form2.passwordAgain"
                type="text"
                placeholder="请再次输入新密码"
                @focus="handleFocus($event, 'passwordAgain')"
                @blur="handleBlur($event, 'passwordAgain', 2)"
                @keydown.enter="retrievePassword"
              />
            </div>
            <span
              :style="{ opacity: validate2.passwordAgain < 2 ? 1 : 0 }"
              style="height: 18.5px; display: block"
            >{{ validateText2.passwordAgain[validate2.passwordAgain] }} </span>
          </div>
          <div style="margin-top: 50px">
            <a-button
              type="primary"
              :loading="loading"
              class="login-form-button"
              @click="retrievePassword"
            > 确定修改 </a-button>
          </div>
        </div>
      </a-form>
    </transition>
    <!-- 找回密码 -->
    <!-- 切换岗位已经弃用 -->
    <transition name="fade-bottom">
      <div
        v-show="visible.selectPost"
        class="extraAction-wrapper"
      >
        <div
          class="top-line-wrapper"
          title="返回登录"
          @click="visible.selectPost = false"
        >
          <div class="img-wrapper">
            <img
              class="img"
              src="~@/assets/user/login/line.png"
              alt=""
            />
          </div>
        </div>
        <div class="extra-title">选择岗位信息</div>
        <div class="select-items-wrapper">
          <a-radio-group v-model="currentPost">
            <a-radio
              v-for="item in postsList"
              :key="item.id"
              :style="{ display: 'block', color: '#ffffff', 'line-height': '30px', height: '30px' }"
              :value="item.id"
              :title="item.pname"
            >
              {{ item.pname }}
            </a-radio>
          </a-radio-group>
        </div>
        <div class="btns-wrapper">
          <a-button
            class="btn"
            type="primary"
            :loading="confirmLoading"
            @click="handleConfirmPost"
          > 进入系统 </a-button>
        </div>
      </div>
    </transition>
    <!-- 切换岗位已经弃用 -->
    <!-- 修改密码 -->
    <!-- <ModalPsw
      :visible="visible.isPwd === 1"
      :query-arg="{
        userName: form.username,
        passWord: form.password,
      }"
      @handleCancel="visible.isPwd = 0"
    /> -->
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import { clientId, clientSecret, PublicKey } from '@/config'
import LoginUtils from '@/utils/loginHelper.js'
import Vue from 'vue'
import { getPostParentName, changeCurrentPost, getCurrentUserBranchCom3, getProjectIdByOrgId } from '@/api/commons.js'
// import ModalPsw from '@/components/avatarDown/modalPsw.vue'
import { updataUserManagePsw, verifyCode } from '@/api/system/system'
import { encryptFromText } from '@/tool/sm.js'
import { loginLog } from '@/api/login'
import setting from '@/config/defaultSettings'
import { getUsedPlatform } from '@/api/gateway'
import { businessQueryList } from '@/api/dataFilter'
export default {
  components: {
    // ModalPsw
  },
  data() {
    return {
      title: setting.title,
      tokenLock: true, // 防止意外情况下获取到token，进入主页
      postsList: [],
      isRemeber: false, // 是否需要记住密码
      loading: false,
      form: {},
      validate: {
        username: 2,
        password: 2
      },
      validateText: {
        username: ['请输入手机号', '', ''],
        password: ['请输入密码', '', '']
      },
      // 修改密码
      form1: {},
      validate1: {
        username: 2,
        password: 2,
        passwordAgain: 2
      },
      validateText1: {
        password: ['请输入新密码', '请输入8到30位密码，密码中必须包含大写小写字母、数字、特殊字符', ''],
        passwordAgain: ['请再次输入新密码', '两次新密码不一致', '']
      },
      // 找回密码
      form2: {},
      validate2: {
        username: 2,
        code: 2,
        password: 2,
        passwordAgain: 2
      },
      validateText2: {
        username: ['请输入手机号', '手机号码格式不正确', ''],
        code: ['请输入验证码', '', ''],
        password: ['请输入新密码', '请输入8到30位密码，密码中必须包含大写小写字母、数字、特殊字符', ''],
        passwordAgain: ['请再次输入新密码', '两次新密码不一致', '']
      },
      // 验证码按钮文字
      // codeText: '发送验证码',
      // 验证码计时器
      timer: null,
      // 验证码秒数
      second: 60,
      // 发送中
      sending: false,
      visible: {
        selectPost: false,
        isPwd: 0
      },
      userInfo: {
        // 用于临时存储用户信息
        employee: {}
      },
      currentPost: '', // 当前岗位ID
      currentPostInfo: {}, // 当前岗位信息（包含级别）
      confirmLoading: false,
      isDev: process.env.NODE_ENV === 'development'
    }
  },
  watch: {
    isRemeber(val) {
      LoginUtils.setRemeber(val || null)
      if (!val) {
        // 如果取消记住密码的勾选，则将本地存储的账号信息清除
        LoginUtils.setAccount(null)
      }
      //开发模式默认选中第一个岗位，因为中建那个账号的岗位太多了，卡的很
    }
  },
  computed: {
    codeText() {
      return this.second === 60 || this.second === 0 ? '发送验证码' : '秒后重发'
    },
    ...mapState({
      // 动态主路由
      mainMenu: (state) => state.permission.addRouters,
      rooterMenus: (state) => state.user.rooterMenus,
      menus: (state) => state.user.menus
    })
  },
  created() {
    this.clearExtraCache()
    this.clearPaginationCache()
    this.resetToken()
    this.resetRoutes()
    this.clearPathCache()
    this.clearBimCache()
    this.initPage()
  },
  beforeDestroy() {
    // 如果没有走正常登录流程，那么就清除token
    if (this.tokenLock) {
      Vue.getAcloudProvider().setAccessToken(null)
    }
  },
  methods: {
    /**
     * 清除额外的缓存
     */
    clearExtraCache() {
      // 施工进度总计划列表到实施管理页面的标识，用于判断项目部的人员是否直接进入实施管理页面
      sessionStorage.removeItem('setPD')
      // 待读消息相关缓存
      this.$store.commit('messageInfo/REMOVE_MESSAGE_COUNT')
    },
    /**
     * 清除页码缓存
     */
    clearPaginationCache() {
      sessionStorage.setItem('cachePagination', JSON.stringify({}))
    },
    /**
     * 重置token
     */
    resetToken() {
      Vue.getAcloudProvider().setAccessToken(null)
    },
    /**
     * 重置标识，使登录后重新获取菜单
     */
    resetRoutes() {
      this.$store.commit('SET_HAS_ROUTERS', false)
    },
    /**
     * 获取岗位列表
     */
    async getPostParentNameReq(userId) {
      try {
        this.postsList = []
        const params = {
          id: userId
        }
        const res = await getPostParentName(params)
        this.postsList = res.data || []
        sessionStorage.setItem('postsList', JSON.stringify(this.postsList))
        // 获取组织标签并存到页面存储
        // const { data: orgLabel } = await findOrgTagListAll({})
        // sessionStorage.setItem('orgLabel', JSON.stringify(orgLabel || []))
        this.getOrgLabel()
        return
      } catch (e) {
        throw new Error(e)
      }
    },
    /**
     * 确认岗位
     */
    async handleConfirmPost() {
      if (!this.currentPost) {
        this.$message.warning('请选择岗位')
        return
      }
      if (this.confirmLoading) return
      this.confirmLoading = true
      const USERINFO = {
        ...this.userInfo,
        currentPost: this.postsList.find((item) => item.id === this.currentPost) || {}
      }
      try {
        await this.changeCurrentPostReq(USERINFO.currentPost.id)

        this.finishLogin(USERINFO)
      } catch (e) {
        this.confirmLoading = false
      }
    },
    async changeCurrentPostReq(postId) {
      try {
        const params = {
          postId
        }
        const res = await changeCurrentPost(params)
        this.currentPostInfo = { ...res.data, projectId: '', projectName: '' } || {}
        if (this.currentPostInfo.code === 'PD') {
          let res2 = await getProjectIdByOrgId({ id: this.currentPostInfo.id })
          if (res2.code === 200) {
            this.currentPostInfo = {
              ...this.currentPostInfo,
              projectId: res2.data.projectId,
              projectName: res2.data.projectName
            }
          }
          let res1 = await getCurrentUserBranchCom3({ tagCodes: ['BC'] })
          if (res1.code === 200) {
            this.currentPostInfo = { ...this.currentPostInfo, ...res1.data[0] }
          }
        } else {
          let company = {
            orgId: this.currentPostInfo.id,
            orgName: this.currentPostInfo.name,
            tagCode: this.currentPostInfo.code
          }
          this.currentPostInfo = { ...this.currentPostInfo, ...company }
        }
      } catch (e) {
        console.error(e)
        throw new Error(e)
      }
    },
    /**
     * 登录完成，存储用户信息，跳转到主页
     */
    finishLogin(userInfo) {
      const updateUserInfo = {
        ...userInfo,
        currentPost: {
          ...this.currentPostInfo, // 这里面的id为组织机构ID
          postId: this.currentPost // 所选择岗位的id
        }
      }
      Vue.getAcloudProvider().setUserInfo(updateUserInfo)
      let level = { CO: 0, BC: 1, PD: 2 }[this.currentPostInfo.code] ?? ''
      if (level || level == 0) sessionStorage.setItem('currentLevel', level)
      this.tokenLock = false // 解开token锁

      let fgs = ''
      if (this.$userType() === 'CO') {
        fgs = this.$currentPost().orgName
      }
      if (this.$userType() === 'BC') {
        fgs = '西南公司,' + this.$currentPost().orgName
      }
      if (this.$userType() === 'PD') {
        fgs = '西南公司,' + this.$currentPost().orgName + ',' + this.$currentPost().name
      }

      this.$store.commit('SET_FGS', fgs)
      // 登录时初始菜单状态为收缩
      localStorage.setItem('initCollapsed','true')

      this.getUsedPlatformFn() //跳转
      // this.$router.push({ path: `/index` })
    },
    /**
     * 初始化页面参数，如果本地已存储有账号，则回显数据
     */
    initPage() {
      this.isRemeber = LoginUtils.getRemeber()
      const accountInfo = LoginUtils.getAccount()
      this.form = {
        ...this.form,
        ...accountInfo
      }
    },
    /**
     * @description: 密码框获取焦点
     * @param {object} e Event事件
     * @return {void}
     */
    handleFocus(e) {
      e.target.setAttribute('type', 'password')
    },
    /**
     * @description: 拾取焦点校验
     * @param {object} e Event事件
     * @param {string} key 字段名
     * @param {number} num 表单编号
     * @return {void}
     */
    handleBlur(e, key, num) {
      // 登录表单
      if (num === 0) {
        if (e.target.value === '' || e.target.value === undefined) {
          this.validate[key] = 0
        } else {
          this.validate[key] = 2
        }
      }
      // 修改初始密码
      if (num === 1) {
        if (e.target.value === '' || e.target.value === undefined) {
          this.validate1[key] = 0
        } else if (key === 'password') {
          const reg = /(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}/
          if (reg.test(e.target.value)) {
            this.validate1[key] = 2
          } else {
            this.validate1[key] = 1
          }
        } else if (key === 'passwordAgain') {
          if (e.target.value === this.form1.password) {
            this.validate1[key] = 2
          } else {
            this.validate1[key] = 1
          }
        }
      }
      // 找回密码
      if (num === 2) {
        if (e.target.value === '' || e.target.value === undefined) {
          this.validate2[key] = 0
        } else if (key === 'username') {
          const reg = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/
          if (reg.test(e.target.value)) {
            this.validate2[key] = 2
          } else {
            this.validate2[key] = 1
          }
        } else if (key === 'code') {
          this.validate2[key] = 2
        } else if (key === 'password') {
          const reg = /(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}/
          if (reg.test(e.target.value)) {
            this.validate2[key] = 2
          } else {
            this.validate2[key] = 1
          }
        } else if (key === 'passwordAgain') {
          if (e.target.value === this.form2.password) {
            this.validate2[key] = 2
          } else {
            this.validate2[key] = 1
          }
        }
      }
    },
    clearBimCache() {
      this.$store.commit('bimInfo/REMOVE_COMP_PRO')
    },
    // 清除tab组件的path缓存数据
    clearPathCache() {
      this.$store.commit('tabInfo/CLEAR_PATHMAP')
      sessionStorage.removeItem('tabPathMap')
      sessionStorage.removeItem('tabPathMapTo')
      sessionStorage.removeItem('tabFullPathList')
      sessionStorage.removeItem('tabPages')
    },
    ...mapActions(['Login', 'Logout', 'GetUserInfo', 'getOrgLabel']),
    async handleSubmit(e) {
      if (this.form.username === undefined || this.form.username === '') {
        this.validate.username = 0
        return
      } else {
        this.validate.username = 2
      }
      if (this.form.password === undefined || this.form.password === '') {
        this.validate.password = 0
        return
      } else {
        this.validate.password = 2
      }
      try {
        if (this.loading) {
          return
        }
        this.loading = true
        //验证成功
        const params = {
          client_id: clientId,
          client_secret: clientSecret,
          username: this.form.username,
          grant_type: 'password_double',
          password: this.doSm3AndSm2Encrypt(this.form.password)
        }
        const res = await this.Login(params)
        const resp = await this.Login(Object.assign(params, { code: res.code, setToken: true }))
        const userInfoRes = await this.GetUserInfo(resp)

        if (userInfoRes && userInfoRes.id) {
          let status = userInfoRes?.employee?.status,
            tags = userInfoRes?.employee?.tags || [],
            isOwner = false
          if (tags.length > 0) {
            isOwner = tags.some((item) => item.tagCode == 'OWNERS')
          }
          if (isOwner) {
            let msg = '该账号为业主用户 请登陆微信小程序使用！'
            this.$notification.error({ message: '警告', duration: null, description: () => <pre>{msg}</pre> })
            return
          } else {
            if (status * 1 === 0) {
              let msg = '您已离职，账号已失效！'
              this.$notification.error({ message: '警告', duration: null, description: () => <pre>{msg}</pre> })
              this.loading = false
              return
            }
          }
          const log = await loginLog({
            employeeId: userInfoRes.employee.id,
            phoneNum: userInfoRes.employee.phoneNum,
            type: 1
          })
          if (log.data.code !== 200) {
            this.$message.warning(log.data.message)
            sessionStorage.removeItem('ycloud-access_token')
            this.loading = false
            return
          }
          if (LoginUtils.getRemeber()) {
            // 如果勾选了记住密码，在登录成功之后，将该账号信息存储在本地
            LoginUtils.setAccount({
              username: this.form.username,
              password: this.form.password
            })
          }
          this.$storageClear('tabs')
          this.$storageClear('tabs-activeKey')
          this.$store.commit('SET_USER', userInfoRes)
          // 获取岗位全路径信息0
          await this.getPostParentNameReq(userInfoRes.id)
          // 添加用户信息到state
          this.userInfo = userInfoRes
          if (!this.postsList.length) {
            this.$message.warning('您当前没有岗位信息，请联系系统管理员')
            throw new Error('post error')
          }
          if (this.postsList[0]) {
            // this.currentPost = this.postsList[0].id // 选中唯一岗位
            // await this.changeCurrentPostReq(this.postsList[0].id)
            let currentPost = this.postsList.find(el=>el.mainPost) || this.postsList[0]
            this.currentPost = currentPost.id // 选中唯一岗位
            await this.changeCurrentPostReq(this.currentPost)
          }
          this.finishLogin({
            ...userInfoRes
          })
          // }
        } else {
          this.loading = false
        }
      } catch (e) {
        console.log(e)
        if (e?.response?.data?.code === '4004') {
          // 登录密码是初始密码
          this.visible.isPwd = 1
          this.form1.username = this.form.username
        }
        this.loading = false
      }
    },
    /**
     * @description: 修改初始密码
     * @return {void}
     */
    updateInitialPassword() {
      const reg = /(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}/
      if (this.form1.password === '' || this.form1.password === undefined) {
        this.validate1.password = 0
        return
      } else if (reg.test(this.form1.password)) {
        this.validate1.password = 2
      } else {
        this.validate1.password = 1
        return
      }
      if (this.form1.passwordAgain === this.form1.password) {
        this.validate1.passwordAgain = 2
      } else {
        this.validate1.passwordAgain = 1
        return
      }
      this.loading = true
      const { password } = this.form
      const { username, password: newPassword } = this.form1
      const params = {
        username: username,
        sign: encryptFromText(username),
        pscode: this.doSm3AndSm2Encrypt(password),
        newPscode: this.doSm3AndSm2Encrypt(newPassword),
        qq: window.btoa(newPassword) // 修改密码时传给后端存储下来
      }
      updataUserManagePsw(params)
        .then(({ status }) => {
          if (status === 200) {
            this.$refs.password1.setAttribute('type', 'text')
            this.$refs.passwordAgain1.setAttribute('type', 'text')
            this.form1 = {
              username: '',
              password: '',
              passwordAgain: ''
            }
            this.form = {
              username: '',
              password: ''
            }
            //密码更改成功
            this.$message.success('修改成功')
            this.visible.isPwd = 0
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    doSm3AndSm2Encrypt(sourceStr) {
      // 密码加密
      /* eslint-disable */
      const sm2Utils = new Sm2Utils()
      const public_key = PublicKey
      const sm3_random_plain = Sm3Utils.encryptFromText(sourceStr) + '|' + sm2Utils.randomWord(8) + '|' + sourceStr
      const sm3_sm2_plain = sm2Utils.encryptFromText(public_key, sm3_random_plain)
      return '{crypto}' + sm3_sm2_plain
      /* eslint-enable */
    },
    /**
     * @description: 发送验证码
     * @param {void}
     * @return {void}
     */
    sendCode() {
      const reg = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/
      if (this.form2.username === '' || this.form2.username === undefined) {
        this.validate2.username = 0
      } else if (reg.test(this.form2.username)) {
        this.validate2.username = 2
        this.sending = true
        verifyCode({ to: this.form2.username })
          .then((res) => {
            if (res.code === 200) {
              this.$message.success('验证码发送成功')
              this.loop()
            } else {
              this.$message.warning(res.data)
            }
          })
          .finally(() => {
            this.sending = false
          })
      } else {
        this.validate2.username = 1
      }
    },
    /**
     * @description: 验证码计时
     * @param {void}
     * @return {void}
     */
    loop() {
      this.timer = setTimeout(() => {
        clearTimeout(this.timer)
        this.timer = null
        if (this.second > 0) {
          this.second--
          this.loop()
        } else {
          this.second = 60
        }
      }, 1000)
    },
    /**
     * @description: 找回密码
     * @param {void}
     * @return {void}
     */
    retrievePassword() {
      const reg = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/
      const regPwd = /(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}/
      if (this.form2.username === '' || this.form2.username === undefined) {
        return (this.validate2.username = 0)
      } else if (reg.test(this.form2.username)) {
        this.validate2.username = 2
      } else {
        return (this.validate2.username = 1)
      }
      if (this.form2.code === '' || this.form2.code === undefined) {
        return (this.validate2.code = 0)
      } else {
        this.validate2.code = 2
      }
      if (this.form2.password === '' || this.form2.password === undefined) {
        return (this.validate2.password = 0)
      } else if (regPwd.test(this.form2.password)) {
        this.validate2.password = 2
      } else {
        return (this.validate2.password = 1)
      }
      if (this.form2.passwordAgain === '' || this.form2.passwordAgain === undefined) {
        return (this.validate2.passwordAgain = 0)
      } else if (this.form2.passwordAgain === this.form2.password) {
        this.validate2.passwordAgain = 2
      } else {
        return (this.validate2.passwordAgain = 1)
      }
      this.loading = true
      const { username, code, password: newPassword } = this.form2
      const params = {
        username: username,
        sign: encryptFromText(username),
        code,
        newPscode: this.doSm3AndSm2Encrypt(newPassword),
        qq: window.btoa(newPassword) // 修改密码时传给后端存储下来
      }
      updataUserManagePsw(params)
        .then(({ status }) => {
          if (status === 200) {
            this.$refs.password2.setAttribute('type', 'text')
            this.$refs.passwordAgain2.setAttribute('type', 'text')
            this.form2 = {
              username: '',
              code: '',
              password: '',
              passwordAgain: ''
            }
            this.form = {
              username: '',
              password: ''
            }
            //密码更改成功
            this.$message.success('修改成功')
            this.visible.isPwd = 0
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // // 根据url查找codes
    // findCodesFromUrl(url) {
    //   const menusList = this.generateList()
    //   const current = menusList.find((item) => item.raw.value === url)
    //   let codes = []
    //   const findCodes = (item) => {
    //     codes.unshift(item.raw.code)
    //     if (item.parentId && menusList.some((menu) => menu.id === item.parentId)) {
    //       findCodes(menusList.find((menu) => menu.id === item.parentId))
    //     }
    //   }
    //   if (!current || current.raw.value === '/index') {
    //     codes = []
    //   } else {
    //     findCodes(current)
    //   }
    //   return codes
    // },
    // 平铺菜单
    // generateList() {
    //   const menusList = []
    //   const fun = (list) => {
    //     list.forEach((item) => {
    //       const { children, ...others } = item
    //       menusList.push(others)
    //       if (!!item.children && !!item.children.length) {
    //         fun(item.children)
    //       }
    //     })
    //   }
    //   fun(this.menus)
    //   return menusList
    // },
    /**
     * @description: 获取常用平台
     * @description: 如果则跳转到该平台 没有则跳转到门户
     * @param {void}
     * @return {void}
     */
    async getUsedPlatformFn() {
      let userInfo = JSON.parse(sessionStorage.getItem('ycloud-user_info'))
      const businessSet = await businessQueryList({ orgId: userInfo.currentPost.id })
      if (businessSet.code === 200) {
        this.$store.commit('SET_BUSINESS_SEARCH_CONDITIONS', {
          detSet: businessSet.data.filter((item) => item.type == 3).map((item) => item.orgId),
          orgSet: businessSet.data.filter((item) => item.type != 3).map((item) => item.orgId)
        })
      }
      let res = await getUsedPlatform(userInfo?.employee?.id)
      let { code, data } = res
      if (code === 200) {
        let activeCodes = []
        if (data?.url) {
          switch (data.name) {
            case '项目管控系统':
              this.$router.push({ path: '/index' })
              return
              break
            case '实时连线与超高清全景监控系统':
              data.url = '/videoDocking/controPanel'
              activeCodes = ['syma', 'video', 'SPPZ', 'KZT']
              break
            case '数据看板系统':
              data.url = '/bi/overview'
              activeCodes = ['opce', 'opce_buka', 'opce_ywkb', 'opce_overview']
              break
            case '客户服务系统':
              data.url = '/complaint/statistics'
              activeCodes = ['prma', 'prma_seex', 'prma_seex_rema', 'seex_crm', 'seex_kfshtj', 'seex_kfsjtj']
              break
            case '组织与岗位绩效考核系统':
              data.url = '/satisfactionManagement/personCheckResult'
              activeCodes = ['inma', 'inma_orpe', 'JX05', 'JX0501']
              break
            default:
              break
          }
          if (!!activeCodes && !!activeCodes.length) {
            this.$store.commit('SET_ACTIVE_CODES', activeCodes)
            this.$storageSet('tabs', [{ title: data.name === '实时连线与超高清全景监控系统' ? '视频监控' : data.name, path: data.url, codes: activeCodes }])
            this.$router.push({ path: data.url })
          } else {
            this.$store.commit('SET_ACTIVE_CODES', [])
            if (data.selectStatus) {
              this.$router.push({ path: '/index' })
            }
          }
        } else {
          this.$router.push('/gateway')
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.extraAction-wrapper {
  .top-line-wrapper {
    cursor: pointer;
    .img-wrapper {
      .img {
        width: 100%;
        object-fit: contain;
      }
    }
  }
  .extra-title,
  .sub-title {
    font-size: 20px;
    color: #ffffff;
    font-weight: bold;
    padding: 15px 0;
    padding-bottom: 40px;
    text-align: center;
    letter-spacing: 0.2em;
  }
  .sub-title {
    font-size: 16px;
    font-weight: normal;
    letter-spacing: 0.1em;
  }
  .select-items-wrapper {
    overflow-y: auto;
    overflow-x: hidden;
    height: 180px;
    .ant-radio-inner {
      background-color: transparent;
      &::after {
        opacity: 1;
        transform: scale(0.7);
        background-color: #ffffff;
      }
    }
    .ant-radio-checked .ant-radio-inner {
      &::after {
        background-color: #1890ff;
      }
    }
    &::-webkit-scrollbar {
      background: transparent;
      width: 8px;
      height: 8px;
    }
    &::-webkit-scrollbar-thumb {
      width: 8px;
      border-radius: 8px;
      background: transparent;
    }
  }
  .btns-wrapper {
    padding: 20px 0;
    display: flex;
    justify-content: center;
    .btn {
      font-size: 16px;
      height: 55px;
      flex: auto;
    }
  }
}
</style>
<style lang="less" scoped>
@default_height: 70px;
@medium_height: 60px;
@mini_height: 55px;
.ant-cascader-menus {
  background: none;
}

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
  -webkit-transition-delay: 99999s;
  -webkit-transition: color 99999s ease-out, background-color 99999s ease-out;
}

#components-form-demo-normal-login.login-form {
  .login-title {
    text-align: center;
    margin-bottom: 25px;
    span {
      margin-bottom: 0;
      font-weight: 500;
      font-size: 34px;
      color: #ffffff;
    }
  }

  .login-form-input {
    width: 100%;
  }

  .input-ctn {
    margin-top: 5px;
    width: 100%;

    .input-item {
      display: flex;
      padding-bottom: 10px;
      border-bottom: 1px solid black;

      input {
        width: 100%;
        margin-left: 10px;
        background: transparent;
        border: none;
        outline: none;
        color: white;
      }
    }

    span {
      opacity: 0;
      transition: all 0.3s;
      color: red;
    }
  }

  .tool-box {
    display: flex;
    justify-content: space-between;
  }

  button {
    color: rgb(232, 240, 254);
    font-size: 16px;
    width: 100%;
    height: @mini_height;
    background: linear-gradient(90deg, #096dd9, #00a9ff);
  }
  .code-btn-wrapper {
    height: 23px;
    width: 100px;
    margin-left: 20px;
    display: flex;
    align-items: center;
    .code-btn {
      border: 1px solid #fff;
      background: transparent;
      outline: none;
      border-radius: 4px;
      height: 35px;
      width: 100%;
      cursor: pointer;
      &:disabled {
        cursor: not-allowed;
      }
    }
  }
}

#components-form-demo-normal-login .login-form-forgot {
  float: right;
}

#components-form-demo-normal-login .login-form-button {
  width: 100%;
}

.tool-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: rgb(232, 240, 254);

  .ant-checkbox-wrapper {
    color: rgb(232, 240, 254);
    opacity: 0.5;
  }

  .pointer {
    cursor: pointer;
    user-select: none;
    opacity: 0.5;
  }

  .ant-checkbox-wrapper:hover,
  .pointer:hover {
    text-decoration: underline;
    opacity: 0.8;
  }
}
</style>
